const q = (css, p = document) => p.querySelector(css);
let ck;

function importData() {
	if (input.value == '') return;
	input.files[0].text().then(txt => {
		const data = JSON.parse(txt);
	});
}

function exportData(obj) {	
	//JSON.stringify 第三个参数是格式符或缩进量
	const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});
	const link = document.createElement('a');
	link.href = URL.createObjectURL(blob);
	link.download = 'metal-data.json';
	link.style.display = 'none';
	document.body.appendChild(link);
	link.click();
	link.remove();
	URL.revokeObjectURL(link.href);
}

function save() {
	const items = { autoWebFull: q('#cbWebFull').checked };
	// -1:禁用  999：随机  0－n:数组某项
	if (!q('#useJX').checked) items.useJX = -1;
	else if (q('#cbRandom').checked) items.useJX = 999;
	else if (ck) items.useJX = ck.closest('tr').rowIndex -1;
	const a = [];
	for (const row of q('table').rows) {
		a.push({
			name: row.cells[1].innerText,
			url: row.cells[2].innerText
		});
	}
	a.shift();
	items.jxUrls = a;

	items.domainWhiteList = q('#txtDomain').value.split('\n');
	items.hostsDisableWebFull = q('#txtNoWebFull').value.split('\n');

	chrome.storage.sync.set(items, function() {
		const r = confirm('已保存，须重新加载扩展才生效！是否刷新？');
		r && chrome.runtime.reload();
	});
}

function config2UI(items) {
	q('#cbWebFull').checked = items.autoWebFull;
	q('#useJX').checked = items.useJX != -1;
	q('#cbRandom').checked = items.useJX == 999;
	q('#txtDomain').value = items.domainWhiteList.join('\n');
	q('#txtNoWebFull').value = items.hostsDisableWebFull.join('\n');

	let cc = `<tr><th width="3%">...</th><th width="12%" align="middle">名称</th>
		<th width="85%" align="middle">URL</th></tr>`;
	for (const k of items.jxUrls) {
		cc += `<tr><td><input type="checkbox"></input></td><td>${k.name}</td><td>${k.url}</td></tr>`;
	}
	q('#tbJX').innerHTML = cc;
}

const validHost = ev => {
	const s = ev.target.value;
	if (!/^[a-z\d\n\.\-_]+$/.test(s)) alert('输入了无效字符！');
	else ev.target.value = s.trim().replace(/\n{2,}/g,'\n');
};
const validURL = s => {
	try {
		new URL(s);
	} catch (ex) {
		return;
	}
	return true;
};

chrome.storage.sync.get(null, config2UI);
q('#tbJX').addEventListener('click', ev => {
	const row = ev.target.closest('tr');
	if (!row || !row.rowIndex) return;

	const e = q('input[type=checkbox]', row);
	e.checked = true;
	if (ck) ck.checked = false;
	ck = e;
});
q('#saveSettings').addEventListener('click', save);
q('#defaultCfg').addEventListener('click', ev => {
	fetch(chrome.runtime.getURL('config.json'))
	.then(r => r.json())
	.then(data => config2UI(data));
});
q('#delRow').addEventListener('click', ev => {
	if (ck && ck.checked) q('#tableJX').deleteRow(ck.closest('tr').rowIndex);
});
q('#addRow').addEventListener('click', ev => {
	const name = q('#txtTitle').value;
	const url = q('#txtURL').value;
	if (!name || !validURL(url)) return;

	q('#tableJX').insertRow(-1)
	.innerHTML = `<td><input type="checkbox"></input></td><td>${name}</td><td>${url}</td>`;
});

q('#txtTitle').addEventListener('blur', ev => {
	const s = ev.target.value.trim();
	if (s != ev.target.value) ev.target.value = s;
	if (!s.length) alert('不能为空！');
});
q('#txtURL').addEventListener('blur', ev => {
	const s = ev.target.value.trim();
	if (s != ev.target.value) ev.target.value = s;
	if (/\s/.test(s)) alert('输入了无效字符！');
	else if (!/^https?:|=$/.test(s) || !validURL(s))
		alert('无效URL');
});
q('#txtDomain').addEventListener('blur', validHost);
q('#txtNoWebFull').addEventListener('blur', validHost);
q('#cbWebFull').addEventListener('click', ev => {
	q('#txtNoWebFull').readOnly = !ev.target.checked;
});